package com.ljq.event.user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author linjq
 * @Date 17/7/28 下午6:07
 */
@Controller
public class UserController {
    private int cnt;

    @Autowired
    private RedisTemplate<String, String> rds;

    @RequestMapping("/t1")
    //@ResponseBody
    public void t1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String port = request.getRequestURL().toString().replace("http://localhost:", ">>>>") + " cnt=>" + cnt++;
        HttpSession s = request.getSession();
        s.setAttribute("username", request.getParameter("username"));

        port += "\tusername="+request.getParameter("username");
        System.out.println(port);


        String key = request.getParameter("username");
        rds.opsForValue().set(key, Math.random()+key);

        PrintWriter pw = response.getWriter();
        Cookie cookie = new Cookie("sessionId", key);
        response.addCookie(cookie);

        //return port;
    }

    @RequestMapping("/t2")
    @ResponseBody
    public String t2(HttpServletRequest request){
        String port = request.getRequestURL().toString().replace("http://localhost:", ">>>>") + " cnt=>" + cnt++;
//        HttpSession s = request.getSession();
//        Object username = s.getAttribute("username");

        Cookie[] cookies = request.getCookies();
        if(cookies!=null) {
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("sessionId")) {
                    String key = cookie.getValue();
                    String session = rds.opsForValue().get(key);
                    port += "\tusername=" + session;
                    break;
                }
            }
        }


        System.out.println(port);

        return port;
    }



}
